package com.xhtt.modules.app.controller;


import com.google.code.kaptcha.Producer;
import com.xhtt.common.utils.R;
import com.xhtt.common.utils.RedisUtils;
import com.xhtt.common.validator.ValidatorUtils;
import com.xhtt.modules.app.form.RegisterForm;
import com.xhtt.modules.sys.service.SysRoleService;
import com.xhtt.modules.sys.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * 注册
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 17:27
 */
@RestController
@RequestMapping("/app")
//@Api("注册接口")
public class AppRegisterController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private Producer producer;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String code = producer.createText();
        //获取图片验证码
        BufferedImage image = producer.createImage(code);
        redisUtils.set(uuid, code, 60);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);
        userService.register(form);
        return R.ok();
    }
}
